local skynet = require "skynet"

local CMD = {}
local SOCKET = {}
local gated, logind
local agent = {}

local function close_agent(fd)
	local a = agent[fd]
	agent[fd] = nil
	if a then
		skynet.call(gate, "lua", "kick", fd)
		-- disconnect never return
		skynet.send(a, "lua", "disconnect")
	end
end

function SOCKET.close(fd)
	print("socket close",fd)
	close_agent(fd)
end

function SOCKET.error(fd, msg)
	print("socket error",fd, msg)
	close_agent(fd)
end

function SOCKET.warning(fd, size)
	-- size K bytes havn't send out in fd
	print("socket warning", fd, size)
end

function SOCKET.data(fd, msg)
end

function CMD.start(conf)
	logind, gated = conf.logind, conf.gated
	return skynet.call(gated, "lua", "open" , conf)
end

function CMD.close(fd)
	close_agent(fd)
end

function CMD.alloc_agent(uid) 
	local agent

	agent = skynet.newservice("agent", skynet.self())

	return agent
end

-- call by gated
function CMD.auth_client_agent(agent, fd, ip) 
	skynet.call(agent, "lua", "auth_client", fd, ip)
end 

skynet.start(function()
	skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
		if cmd == "socket" then
			local f = SOCKET[subcmd]
			f(...)
			-- socket api don't need return
		else
			local f = assert(CMD[cmd])
			skynet.ret(skynet.pack(f(subcmd, ...)))
		end
	end)
end)
